import django_filters
from django.db.models import Q
from django_filters.rest_framework import NumberFilter, FilterSet, CharFilter

from app.goods.models import Goods


class GoodsFilter(FilterSet):
    '''
        price_min:销售最低价
        price_max:销售最高价
    '''

    price_min = NumberFilter(field_name='shop_price', lookup_expr='gte', help_text='最低价')
    price_max = NumberFilter(field_name='shop_price', lookup_expr='lte', help_text='最低价')
    sold_num = NumberFilter(field_name='sold_num', help_text='销售量')
    category = CharFilter(field_name='category',
                          method='gain_category',
                          help_text='商品分类名称')

    def gain_category(self, queryset, name, value):
        return Goods.objects.filter(Q(category__name__contains=value) |
                                    Q(category__parent_category__name__contains=value) |
                                    Q(category__parent_category__parent_category__name__contains=value))

    class Meta:
        model = Goods
        fields = ['price_min', 'price_max', 'sold_num', 'is_hot', 'is_new']
